package com.ndphu.comic.gui.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.ndphu.comic.R;
import com.ndphu.comic.gui.fragment.readnow.FragmentReadNow;
import com.ndphu.comic.gui.fragment.searchbook.FragmentOnlineSearch;
import com.ndphu.comic.gui.utils.Utils;
import com.ndphu.comic.io.extend.AsyncTask;
import com.ndphu.comic.io.processor.TruyenTranhTuanProcessor;
import com.ndphu.comic.io.processor.VNSharingProcessor;
import com.ndphu.comic.model.BookEntry;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends FragmentActivity {

	public static final String PREF_RECENT_BOOKS = "recent_books";
	public static final String PREF_RECENT_BOOKS_LIST = "recent_book_list";

	public static final String PREF_BOOK = "book";

	public static final String PREF_BOOKS_DB = "books_db";

	public static final String PREF_BOOKS_DB_VALUE = "value";

	public static final String PREF_IMAGE_CACHE = "image_cache";

	private SharedPreferences mBooksDbPref;

	public static final String EXTRA_BOOK_URL = "book_url";
	public static final String EXTRA_BOOK_SOURCE = "book_source";
	public static final String EXTRA_BOOK_COVER_URL = "book_cover_url";
	public static final String EXTRA_BOOK_NAME = "book_name";
	public static final String EXTRA_BOOK_DESC = "book_description";

	public static final String SOURCE_VNSHARING = "VNSHARING";
	public static final String SOURCE_TRUYENTRANHTUAN = "TRUYENTRANHTUAN";
	public static final String SOURCE_MANGA24H = "MANGA24H";

	public static final int NUMBER_OF_RECENT_BOOKS = 20;

	public static final List<BookEntry> LIST_BOOK_ENTRY = new ArrayList<BookEntry>();

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private String[] mMainMenuList = new String[] { "Read Now", "Search Book" };
	private int mSelectedMenu = 0;
	private Fragment mCurrentFragment;
	private CharSequence mTitle;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mBooksDbPref = getSharedPreferences(PREF_BOOKS_DB, Context.MODE_APPEND);
		setContentView(R.layout.activity_main);
		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mMainMenuList));
		mDrawerList.setOnItemClickListener(mDrawerItemClickListener);
		initDrawerToggle();
		getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new FragmentReadNow()).commit();
		mDrawerList.setItemChecked(0, true);
		// checkCachedBookEntry();
	}

	@SuppressLint("NewApi")
	private void initDrawerToggle() {
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {

			/** Called when a drawer has settled in a completely closed state. */
			public void onDrawerClosed(View view) {
				super.onDrawerClosed(view);
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu();
			}

			/** Called when a drawer has settled in a completely open state. */
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	private void checkCachedBookEntry() {
		try {
			if (mBooksDbPref.contains(PREF_BOOKS_DB_VALUE)) {
				new AsyncTask<Void, Void, Void>() {
					private ProgressDialog mDialog;

					@Override
					protected void onPreExecute() {
						super.onPreExecute();
						this.mDialog = Utils.getProgressDialog(MainActivity.this, "Loading",
								"Loading offline book entries", false, null);
						this.mDialog.show();
					}

					@Override
					protected Void doInBackground(Void... params) {
						try {
							JSONArray array = new JSONArray(mBooksDbPref.getString(PREF_BOOKS_DB_VALUE, ""));
							LIST_BOOK_ENTRY.clear();
							for (int i = 0; i < array.length(); ++i) {
								JSONObject bookEntryJson = array.getJSONObject(i);
								BookEntry entry = new BookEntry();
								entry.bookName = bookEntryJson.getString("bookName");
								entry.bookSource = bookEntryJson.getString("bookSource");
								entry.bookUrl = bookEntryJson.getString("bookUrl");
								LIST_BOOK_ENTRY.add(entry);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						super.onPostExecute(result);
						Toast.makeText(MainActivity.this,
								LIST_BOOK_ENTRY.size() + " books are available for offline search", Toast.LENGTH_SHORT)
								.show();
						mDialog.dismiss();
					}

				}.execute();
			} else {
				// Start caching process
				new AsyncTask<Void, String, Void>() {
					ProgressDialog mDialog;

					@Override
					protected void onPreExecute() {
						super.onPreExecute();
						this.mDialog = Utils.getProgressDialog(MainActivity.this, "Loading", "", false, null);
						this.mDialog.show();
					}

					@Override
					protected void onProgressUpdate(String... values) {
						super.onProgressUpdate(values);
						this.mDialog.setMessage(values[0]);
					}

					@Override
					protected Void doInBackground(Void... params) {
						synchronized (LIST_BOOK_ENTRY) {
							LIST_BOOK_ENTRY.clear();
						}
						this.publishProgress("Get all books from truyen.vnsharing.com");
						Map<String, String> data = new HashMap<String, String>();
						data.put("mangaName", "");
						data.put("authorArtist", "");
						data.put("group", "");
						data.put("genres", "0");
						data.put("status", "");
						try {
							List<BookEntry> VNSharingBooks = VNSharingProcessor.searchFromVNSharing(data);
							synchronized (LIST_BOOK_ENTRY) {
								LIST_BOOK_ENTRY.addAll(VNSharingBooks);
							}
						} catch (Exception ex) {
							ex.printStackTrace();
						}

						this.publishProgress("Get all books from truyentranhtuan.com");
						try {
							List<BookEntry> truyenTranhTuanBooks = TruyenTranhTuanProcessor.getAllBookEntries();
							synchronized (LIST_BOOK_ENTRY) {
								LIST_BOOK_ENTRY.addAll(truyenTranhTuanBooks);
							}
						} catch (Exception ex) {
							ex.printStackTrace();
						}

						this.publishProgress("Get all books from manga24h.com");
						// try {
						// List<BookEntry> truyenTranhTuanBooks =
						// Manga24hProcessor2.getAllBookEntries();
						// synchronized (LIST_BOOK_ENTRY) {
						// LIST_BOOK_ENTRY.addAll(truyenTranhTuanBooks);
						// }
						// } catch (Exception ex) {
						// ex.printStackTrace();
						// }

						this.publishProgress("Sorting result");
						synchronized (LIST_BOOK_ENTRY) {
							Collections.sort(LIST_BOOK_ENTRY, new Comparator<BookEntry>() {

								@Override
								public int compare(BookEntry lhs, BookEntry rhs) {
									return lhs.bookName.compareTo(rhs.bookName);
								}
							});
						}
						this.publishProgress("Saving to cache");
						JSONArray array = new JSONArray();
						synchronized (LIST_BOOK_ENTRY) {
							for (BookEntry entry : LIST_BOOK_ENTRY) {
								JSONObject bookJson = new JSONObject();
								try {
									bookJson.put("bookName", entry.bookName);
									bookJson.put("bookUrl", entry.bookUrl);
									bookJson.put("bookSource", entry.bookSource);
								} catch (JSONException e) {
									e.printStackTrace();
								}
								array.put(bookJson);
							}
						}
						mBooksDbPref.edit().remove(PREF_BOOKS_DB_VALUE)
								.putString(PREF_BOOKS_DB_VALUE, array.toString()).commit();
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						super.onPostExecute(result);
						mDialog.dismiss();
					}
				}.execute();
			}
		} catch (Exception ex) {

		}
	}

	private OnItemClickListener mDrawerItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
			selectItem(position);
		}
	};

	private void selectItem(int position) {
		FragmentManager fragmentManager = getSupportFragmentManager();
		mCurrentFragment = null;
		mSelectedMenu = position;
		switch (position) {
		case 0:
			mCurrentFragment = new FragmentReadNow();
			break;
		case 1:
			mCurrentFragment = new FragmentOnlineSearch();
			break;
		case 2:
			Intent intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			return;
		default:
			break;
		}
		fragmentManager.beginTransaction().replace(R.id.content_frame, mCurrentFragment).commit();

		// Highlight the selected item, update the title, and close the drawer
		mDrawerList.setItemChecked(position, true);
		mDrawerLayout.closeDrawer(mDrawerList);
		supportInvalidateOptionsMenu();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		switch (mSelectedMenu) {
		case 1:
			menu.findItem(R.id.action_advance_search).setVisible(true);
			break;
		default:
			menu.findItem(R.id.action_advance_search).setVisible(false);
			break;
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		switch (item.getItemId()) {
		case R.id.action_settings:
			Intent intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			break;
		case R.id.action_advance_search:
			((FragmentOnlineSearch) mCurrentFragment).showAdvanceSearch();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);

	}
}
